import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { CommonDialog } from '../../../components/common/Dialog';
import WarningService from '../_common/service';
import { ApprovingItem } from '../_component/ApprovingItem';
import MethodUtil from '../../../utils/MethodUtil';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const arrowIcon = require('../../../imgs/sanjiao3.png')

const TAB_LIST = [
	{
		name: '审批中',
		key: 'auditingCnt',
		id: 1,
		count: 0,
	},
	{
		name: '审批驳回',
		key: 'auditRejectCnt',
		id: 0,
		count: 0,
	}
]
/**
* order: 化销成交报告
* order_change: 订单变更
* zxy_order: 中新油成交报告
* zxy_order_cancel: 中新油交报告撤销
* qh_order_abandone: 泉化订单作废
* creditInfo: 授信申请、变更
* company_create: 企业创建
* company_assign: 企业认
 */

export class ApprovingWarning extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { tabIndex, headTitle } = navigation.state.params || {};
		return {
			headerTitle: headTitle || TAB_LIST[tabIndex || 0].name,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		let { tabIndex } = props.navigation.state.params || {};
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false, // 下拉刷新图标
			modalVisible: false,
			approveCntInfo: {},
			tabIndex: tabIndex || 0,
			curType: 'order',
			curTypeName: '化销成交',
			choice: {}
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			auditType: 'order',
			auditStatus: TAB_LIST[tabIndex || 0].id,
			pageNo: 1,
			pageSize: 10,
		}
	}

	async componentWillMount() {
		await this.getSorage();
		await this.getRecord();
		await this.initPage();
	}

	//获取业务组织
	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			choice: {
				corpId: userInfo.corpId || '',
				corpName: userInfo.corpName || '',
			}
		})
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.pageParams.auditStatus = TAB_LIST[this.state.tabIndex].id;
		this.pageParams.corpId = this.state.choice.corpId;
		let res = await WarningService.getApprovingList(this.pageParams); // TODO
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				curTypeCnt: res.recordCount || 0
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	async getRecord() {
		let res = await WarningService.getApprovingAuditCnt({ corpId: this.state.choice.corpId });
		this.setState({
			approveCntInfo: res,
		})
	}


	// 刷新页面 ifSearch--搜索时设置为true,刷新每个类型查询出的数量设置curTypeCnt。切换类型时不设置curTypeCnt，防止数字出现频繁出现切换的问题
	reloadPage(ifSearch) {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.getRecord();
		this.initPage();
		this.setState({ ifSearch })
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.getRecord();
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	//切换审批状态
	changeTab(index) {
		if (this.state.tabIndex === index) return;
		this.pageParams.searchKey = '';
		this.props.navigation.setParams({
			headTitle: TAB_LIST[index].name
		})
		this.setState({
			tabIndex: index
		}, () => {
			this.reloadPage();
		})
	}

	//切换任务
	changeType(type, name) {
		if (this.state.curType === type) return;
		this.pageParams.auditType = type
		this.pageParams.searchKey = '';
		this.setState({
			curType: type,
			curTypeName: name
		}, () => {
			this.reloadPage();
		})
	}

	// 搜索View
	_renderFilterWrap() {
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchKey}
						onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
						onSubmitEditing={() => { this.reloadPage(true); }}
					/>
				</View>
			</View>
		)
	}


	// 如何处理 View
	_renderToastWrap = () => {
		return (
			<View>
				<Text style={styles.toasText}>审批业务类型：</Text>
				<Text style={styles.toasText}>1.化销成交报告：<Text style={styles.toasTextRight}>“现货采购、现货销售、长约执行（有变更）、代理销售、闭口销售”</Text></Text>
				<Text style={styles.toasText}>2.新油成交：<Text style={styles.toasTextRight}>“新油采购、新油销售、新油闭口”</Text></Text>
				<Text style={styles.toasText}>3.新油撤销：<Text style={styles.toasTextRight}>“新油撤销审批”</Text></Text>
				<Text style={styles.toasText}>4.订单变更：<Text style={styles.toasTextRight}>“订单变更审批”</Text></Text>
				<Text style={styles.toasText}>5.泉化作废：<Text style={styles.toasTextRight}>“泉化销售单作废”</Text></Text>
				<Text style={styles.toasText}>6.授信申请：<Text style={styles.toasTextRight}>“授信申请、变更”</Text></Text>
				<Text style={styles.toasText}>7.企业创建：<Text style={styles.toasTextRight}>“创建企业”</Text></Text>
				<Text style={styles.toasText}>8.企业认领：<Text style={styles.toasTextRight}>“企业认领”</Text></Text>
				<Text style={styles.toasText}>审批中业务仅针对业务方发起，其他付款、价格、计划等相关业务审批请在对应模块中查询</Text>
			</View>
		)
	}


	//tab View
	_renderTabWrap() {
		const { approveCntInfo, tabIndex } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						const totalCnt = approveCntInfo && approveCntInfo[item.key] ? approveCntInfo[item.key].totalCnt : 0;
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
								<Text style={[styles.tabText, tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
								<Text style={[styles.tabText, styles.tabCount, tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{totalCnt}</Text>
							</TouchableOpacity>
						)
					})
				}
				<TouchableOpacity activeOpacity={1} onPress={() => { this.setState({ modalVisible: true }) }}>
					<Image style={{ tintColor: '#fff' }} source={require('../../../imgs/global/query.png')} />
				</TouchableOpacity>
			</View>
		)
	}

	_renderTypesWrap() {
		const { approveCntInfo, tabIndex, curType, curTypeCnt, ifSearch } = this.state;
		const curKey = TAB_LIST[tabIndex].key;
		const typeList = approveCntInfo && approveCntInfo[curKey] ? approveCntInfo[curKey].cntList : null;
		return (
			<View style={styles.typesWrap}>
				{
					typeList && typeList.length && typeList.map((item, index) => {
						const checkedTextStyle = curType == item.taskType ? { color: '#fff' } : { color: style.color.themeColor };
						const checkedStyle = curType == item.taskType ? { backgroundColor: style.color.themeColor } : { backgroundColor: null };
						const typeCnt = curType == item.taskType && ifSearch ? curTypeCnt : item.totalCnt;
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeType(item.taskType, item.cntName) }} key={index} style={[styles.typesItem, checkedStyle]}>
								<Text style={[styles.typeText, checkedTextStyle]}>{item.cntName}</Text>
								{/* <Text style={[styles.typeText, checkedTextStyle]}>{typeCnt}</Text> */}
								{typeCnt ? <View style={[styles.redCircle, { backgroundColor: curType == item.taskType ? '#fff' : 'red' }]}></View> : null}
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	//跳详情
	_details = (sendData) => {
		this.props.navigation.navigate('EnterpriseDetailsPage',
			{
				companyId: sendData.companyId,
				title: sendData.companyName,
				status: 'PASS',
				listType: '我的客户',
				initialPage: this.state.tabIndex ? 7 : 4, // 显示第几个tab
			})
	}

	_renderListItem = (data) => {
		let { curType, curTypeName, tabIndex, choice } = this.state;
		let { navigate } = this.props.navigation;
		let itemData = data.item || {};
		console.log(curType)
		if (curType == 'creditInfo') {
			const { companyName, createDate } = itemData;
			return (
				<View style={styles.listItem}>
					<RowItemTitle left={companyName || '-'} right={(createDate || '-').substring(0, 16)} />
					{this._renderCreditInfoItem(itemData)}
				</View>
			)
		} else if (curType == 'company_create') {
			let { companyName, companyId, applyId, createDate, bizTeamName, organName, staffName, applyType } = itemData || {};
			return (
				<View style={styles.listItem}>
					<RowItemTitle left={companyName || '-'} right={(createDate || '-').substring(0, 16)} />
					<Text style={{ fontSize: 10 * scale, paddingTop: 0, color: '#848A96' }}>(业务组织：{choice.corpName || '-'})</Text>
					<TouchableOpacity onPress={() => {
						// navigate('EnterpriseDetailsPage', {
						// 	companyId,
						// 	id: applyId,
						// 	title: companyName,
						// 	status: tabIndex ? 'UNPASS' : 'PASS' //请求不同接口
						// })
						navigate('EnterpriseDetailsPage', {
							tabIndex: 0,
							companyId: companyId,
							id: applyId,
							title: companyName,
							status: 0,
							choice
						})
					}}>
						<Row left={(staffName || '') + ' | ' + (bizTeamName || '-') + ' | ' + (organName || '-')} right={applyType == 'ADD' ? '企业创建' : '企业变更'} />
					</TouchableOpacity>
				</View>

			)
		} else if (curType == 'company_assign') {
			let { companyName, staffName, bizTeamName, organName, createDate } = itemData || {};
			return (
				<View style={styles.listItem}>
					<RowItemTitle left={companyName || ''} right={(createDate || '-').substring(0, 16)} />
					<Text style={{ fontSize: 10 * scale, paddingTop: 0, color: '#848A96' }}>(业务组织：{choice.corpName || '-'})</Text>
					<TouchableOpacity onPress={() => {
						navigate('ClaimListPage', {
							listType: 'A',
							status: tabIndex ? 'UNPASS' : 'AUDITTING',
							choice
						})
					}} >
						<Row left={(staffName || '-') + ' | ' + (bizTeamName || '-') + ' | ' + (organName || '-')} right={'企业认领'} />
					</TouchableOpacity>
				</View>
			)
		}
		else if (curType == 'rebateApply') {
			let { item } = data
			let { rebateMonth } = item
			if (rebateMonth) {
				rebateMonth = rebateMonth.slice(4)
				if (Number(rebateMonth) >= 10) {
					rebateMonth = rebateMonth
				}
				else {
					rebateMonth = rebateMonth.slice(1)
				}
			}
			return (
				<TouchableOpacity style={{
					marginBottom: 20 * scale,
				}}
					onPress={() => {
						this.props.navigation.navigate('RebateDetailPage', {
							data: item,
							type: 'noApply'
						})
					}}
				>
					<View style={styles.itemWrap}>
						<View style={{ marginBottom: 10 * scale, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
							<Text style={styles.itemLightText}>{item.applyId || '--'}</Text>
							<Image source={arrowIcon} style={styles.arrowIcon} />
						</View>
						<View style={styles.itemBorder}></View>
						<View>
							<View style={styles.itemTypeBox}>
								<View style={styles.itemType}>
									<Text style={styles.itemTypeTitle}>优惠标题：</Text>
								</View>
								<Text style={styles.itemTypeText}>
									{item.rebateName || '--'}
								</Text>
							</View>
							<View style={styles.itemTypeBox}>
								<View style={styles.itemType}>
									<Text style={styles.itemTypeTitle}>返利品类：</Text>
								</View>
								<Text style={styles.itemTypeText}>
									{item.groupItemList && item.groupItemList.map((i, index) => {
										if (index < item.groupItemList.length - 1) {
											return (
												i.groupName + '（' + i.regionNames + '）' + '/'
											)
										}
										else {
											return (
												i.groupName + '（' + i.regionNames + '）'
											)
										}
									})}
								</Text>
							</View>
							<View style={styles.itemTypeBox}>
								<View style={styles.itemType}>
									<Text style={styles.itemTypeTitle}>返利执行：</Text>
								</View>
								<Text style={styles.itemTypeText}>
									{rebateMonth + '月'}
								</Text>
							</View>
							<View style={styles.itemTypeBox}>
								<View style={styles.itemType}>
									<Text style={styles.itemTypeTitle}>申请人：</Text>
								</View>
								<Text style={styles.itemTypeText}>
									{item.submitByName}
									{item.staffLineName ? '（' + item.staffLineName + '）' : null}
								</Text>
							</View>
						</View>
					</View>
				</TouchableOpacity>
			)
		}
		else {
			return (
				<View>
					<ApprovingItem choice={choice} data={data.item} status={curType} statusName={curTypeName} navigation={this.props.navigation} />
				</View>
			)
		}
	}

	_renderCreditInfoItem(data) {
		const { taskName, creditKind, bizTeamName, applyAmount, accountDay, creditEndDate, staffName, organName, companyId } = data;
		const { choice } = this.state;
		return (
			<TouchableOpacity style={styles.creditInfo} right={'授信申请'} onPress={() => {
				this.props.navigation.navigate('EnterpriseDetailsPage', {
					companyId,
					currentCreditType: creditKind == 'SX' ? 2 : 1,
					creditApplyStatus: '2X',  //列表类型：待审批
					initialPage: 7,
					status: 'PASS',
					choice
				})
			}} >
				<View style={styles.creditInfoTitle}>
					<Row left={'授信账户申请'} />
					<Text style={{ fontSize: 10 * scale, padding: 14 * scale, paddingTop: 0, color: '#848A96' }}>(业务组织：{choice.corpName || '-'})</Text>
				</View>
				<Row left={taskName + '账户'} right={'¥' + (MethodUtil.toThousands(applyAmount, 2) || 0) + '元'} leftStyle={{ fontWeight: '700' }} rightStyle={{ color: '#000' }} />
				<Text style={styles.creditInfoDay}>账期：{accountDay || 0}天 | 有效期至{creditEndDate || '-'}</Text>
				<Text style={styles.creditInfoDay}>
					{staffName || '-'} | {bizTeamName} | {organName || '-'}
				</Text>
			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, modalVisible } = this.state;
		return (
			<View style={styles.container}>
				{this._renderFilterWrap()}
				{this._renderTabWrap()}
				{this._renderTypesWrap()}
				{
					status == 'data' ? (<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
						<FlatList
							data={listData}
							style={{ marginLeft: 12 * scale, marginRight: 12 * scale }}
							renderItem={this._renderListItem}
							refreshing={refreshIcon}
							onRefresh={() => { this.refresh() }}
							onEndReachedThreshold={0.1}
							onEndReached={() => { this.loadMore() }}
						/>
					</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}
				<CommonDialog
					modalVisible={modalVisible}
					title={'提示'}
					onClosePress={() => { this.setState({ modalVisible: false }) }}
					renderCustom={this._renderToastWrap} />
			</View>
		)
	}
}

function Row(props) {
	const { left, right, leftStyle, rightStyle } = props;
	return (
		<View style={styles.row}>
			<Text style={[styles.rowText, styles.rowLeftText, leftStyle]}>{left}</Text>
			<Text style={[styles.rowText, styles.rowRightText, rightStyle]}>{right}</Text>
		</View>
	);
}

function RowItemTitle(props) {
	const { left, right } = props;
	return (
		<View style={styles.spaceBetween}>
			<Text style={styles.rowItemTitleText}>{left}</Text>
			<Text style={styles.rowItemTitleText}>{right}</Text>
		</View>
	);
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 290 * scale,
		paddingLeft: 60 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 24 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingLeft: 18 * scale,
		paddingRight: 18 * scale,
	},
	tabText: {
		color: '#fff',
		textAlign: 'center'
	},
	tabCount: {
		marginTop: 4 * scale
	},
	tabItem: {
		paddingTop: 14 * scale,
		paddingBottom: 12 * scale,
	},
	listItem: {
		borderRadius: 4 * scale,
		marginBottom: 22 * scale
	},
	userInfo: {
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
		paddingBottom: 6 * scale,
		paddingTop: 8 * scale,
		borderStyle: 'solid',
		borderTopColor: '#E3E7F0',
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
	},
	warningItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 13 * scale
	},
	userName: {
		fontSize: 12 * scale,
		marginBottom: 4 * scale,
		opacity: .8
	},
	typesWrap: {
		width: '100%',
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
		marginTop: 14 * scale
	},
	typesItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		marginLeft: '4%',
		marginTop: 13 * scale,
		padding: 8 * scale,
		width: '20%',
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		borderRadius: 20 * scale
	},
	typeText: {
		fontSize: 11 * scale,
		fontWeight: '700',
		paddingLeft: 3 * scale,
		paddingRight: 3 * scale,
	},
	redCircle: {
		position: 'absolute',
		top: 4 * scale,
		right: 8 * scale,
		height: 4 * scale,
		width: 4 * scale,
		backgroundColor: 'red',
		borderRadius: 6 * scale
	},
	toasText: {
		fontSize: 12 * scale,
		marginBottom: 14 * scale
	},
	toasTextRight: {
		fontWeight: '700'
	},
	row: {
		flexDirection: 'row',
		height: 42 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		backgroundColor: '#fff',
		padding: 14 * scale,
		marginTop: 6 * scale,
		borderRadius: 8 * scale
	},
	rowItemTitleText: {
		fontSize: 12 * scale,
		color: '#848A96'
	},
	spaceBetween: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginBottom: 6 * scale
	},
	rowText: {
		fontSize: 12 * scale
	},
	rowLeftText: {
		color: '#000000'
	},
	rowRightText: {
		color: '#F60202',
		fontWeight: '800'
	},
	creditInfo: {
		backgroundColor: '#fff',
		borderRadius: 8 * scale,
		paddingBottom: 14 * scale
	},
	creditInfoTitle: {
		borderBottomWidth: 1 * scale,
		borderBottomColor: '#D8D8D8',
		borderBottomWidth: 1 / PixelRatio.get()
	},
	creditInfoDay: {
		color: '#000',
		opacity: 0.6,
		fontSize: 12 * scale,
		textAlign: 'right',
		paddingRight: 14 * scale,
		paddingBottom: 4 * scale,
	},
	itemLightText: {
		fontSize: 12 * scale,
		color: '#000000',
		fontWeight: '600',
	},
	itemWrap: {
		backgroundColor: '#fff',
		width: '100%',
		borderRadius: 8 * scale,
		// paddingLeft: 12 * scale,
		paddingTop: 11 * scale,
		// paddingBottom: 14 * scale,
	},
	itemType: {
		width: 70 * scale,
		flexDirection: 'row',
		// alignItems: 'flex-end',
		justifyContent: 'flex-end',
		borderRadius: 4 * scale,
		marginRight: 10 * scale,
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	arrowIcon: {
		width: 8 * scale,
		height: 12 * scale,
		position: 'absolute',
		right: 0,
		top: 2 * scale,
		right: 12 * scale,
	},
	itemTypeBox: {
		flexDirection: 'row',
		marginBottom: 15 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	itemTypeTitle: {
		color: '#030303',
		opacity: 0.61,
		fontSize: 12 * scale,
	},
	itemTypeText: {
		color: '#000000',
		fontSize: 12 * scale,
		fontWeight: '600',
		width: 230 * scale,
	}
})